"""
这个代码删除大小异常，亮度异常，分辨率异常的图片
"""
import cv2
import os
import shutil
from torch.nn.functional import tanh
from tqdm import tqdm
import numpy as np
from adjust_image_britness import RGBAlgorithm
from PIL import Image
images_path =r"/media/liyan/3b75ab20-92d3-4be6-81c2-4e1798e2fe16/我的数据集/图像分类数据集/总/"
resize_shape = [480,480]
#自适应亮度增强的系数
k = -0.02
c = 1

def get_brightness(img_name:str):
    '''
    获取图片亮度，返回图片的RGB三通道的平均值，返回图片
    '''
    rgb_image = cv2.imread(img_name)
    rgb_image = cv2.cvtColor(rgb_image,cv2.COLOR_BGR2RGB)
    brightness_mean = cv2.mean(rgb_image)
    return (round(brightness_mean[0])+
            round(brightness_mean[1])+
            round(brightness_mean[2]))/3,rgb_image

def get_lightness(src_img):
    '''
    计算图像的HSV亮度，返回亮度值
    H:色调
    S:饱和度
    V:明度
    '''
    src_img = cv2.imread(src_img)
    hsv_image = cv2.cvtColor(src_img, cv2.COLOR_BGR2HSV)
    lightness = hsv_image[:, :, 2].mean()
    return lightness,src_img

def get_size(img_name:str):
    '''
    获取图片长宽，返回(width,height),bgr_image
    '''
    bgr_image = cv2.imread(img_name)
    height,width = bgr_image.shape[0],bgr_image.shape[1]
    return (width,height),bgr_image

#----------------------------------主体--------------------------------------
for top,dirs,files in os.walk(images_path):
    for dir in dirs:
        file_path = os.path.join(top,dir)
        del_list = []
        img_files = [os.path.join(file_path, file) for file in os.listdir(file_path) if (file.endswith('.jpg'))]
        for index,images_name in tqdm(enumerate(img_files),ncols=150):
            file_name = images_name.split(os.sep)[-1][:-4]

            # brit,img = get_lightness(images_name)      #获取图片亮度
            # if brit >= 190 or brit <50:                 #自适应亮度增强
            #     img = RGBAlgorithm(img,value=(k*brit+c),basedOnCurrentValue=True)
            #     cv2.imwrite(images_name,(img*255).astype(img.dtype))

            size,img = get_size(images_name)        #图片分辨率
            # if min(size) < 20 or ( max(size) / min(size) )>= 2.5:                      #分辨率太小
            #     del_list.append(img_files.pop(index))
            #     print("\n删除一个分辨率异常的图片")
            if max(size) > 480:                  #分辨率太大
                new_img = cv2.resize(img,dsize=resize_shape)
                cv2.imwrite(images_name,new_img)
                print("\n移动 resize了一个过大图片")

            file_size = os.path.getsize(img_files[index])  # 返回文件大小
            if file_size < 2048:
                del_list.append(img_files.pop(index))
                print(f'\n删除了一个小文件')

        print("------------执行删除-----------------------------")
        for image in del_list:
            os.remove(image)           #删除
        print("--------------删除完毕--------------------------")
